import React, { FC, useState, ChangeEvent, useEffect } from "react";
import { useNavigate, useLocation, useSearchParams } from "react-router-dom";
import { Input } from "antd";
//引入常用变量
import { SEARCH_PARAMS_KEY } from "../../constant";
const { Search } = Input;
const SearchInput: FC = () => {
  const nav = useNavigate();
  const { pathname } = useLocation();
  const [searchdata, setsearchdata] = useState<string>("");
  //获取路由参数
  const [urlparams] = useSearchParams();
  useEffect(() => {
    setsearchdata(urlparams.get(SEARCH_PARAMS_KEY) || "");
  }, [urlparams]);
  const onSearch = () => {
    //搜索结果保存到路径
    nav({
      pathname,
      search: `${SEARCH_PARAMS_KEY}=${searchdata}`,
    });
  };
  const searchhandle = (e: ChangeEvent<HTMLInputElement>) => {
    setsearchdata(e.target.value);
  };
  return (
    <>
      <Search allowClear placeholder="请输入搜索" value={searchdata} onSearch={onSearch} onChange={searchhandle} />
    </>
  );
};

export default SearchInput;
